# coding:utf-8
# @Time     : 2018/9/26 下午3:20
# @Author   : 程杨
# @Discribe : 上线单条用户测试
import jieba
import pandas as pd
import traceback
from common.logger import Logger


class Input_ContactExtractor():
    def __init__(self):
        self._apply_id = None
        self.logger = Logger("input_score.log").getLogger()


    def get_input_feature(self, imei, input_data, tfidf_model):
        data = pd.DataFrame(input_data)
        data['imei'] = imei
        data['input_info'] = data['content'].astype('str').apply(lambda x: ' '.join(jieba.cut_for_search(x.strip(), HMM=True)))
        process_data = data.groupby('imei')['input_info'].agg(lambda x: '{}'.format(' '.join(x))).reset_index()
        values = tfidf_model.transform(process_data['input_info'].fillna('').astype('str')).astype(float)
        return values

    def parse(self, imei, input_data, tfidf_model, input_model):
        from collections import OrderedDict
        res = OrderedDict()
        if len(input_data) == 0:
            res['input_score'] = 1000
            self.logger.info('empty input data')
            return res
        try:
            values = self.get_input_feature(imei, input_data, tfidf_model)
            score = round(input_model.predict_proba(values)[0][1] * 1000, 2)
        except Exception as e:
            err_message = traceback.format_exc(limit=1)
            self.logger.info("appid:" + str(self._apply_id) + ' ' + err_message)
            self._apply_id = None
            res['input_score'] = 1000
            return res
        res['input_score'] = score
        return res



